package cool.mtc.web.result;

import cool.mtc.core.result.Result;
import cool.mtc.core.util.StringUtil;

/**
 * @author yz
 */
public class ResultHandler {

    public <T> void handleMsgArgs(Result<T> result) {
        if (StringUtil.isEmpty(result.getMsg()) || !result.getMsg().contains("{") || !result.getMsg().contains("}")) {
            return;
        }
        if (null == result.getArgs() || result.getArgs().length == 0) {
            return;
        }
        String msg = this.replacePlaceholders(result.getMsg(), result.getArgs());
        result.setMsg(msg);
    }

    private String replacePlaceholders(String msg, Object... args) {
        for (int i = 0; i < args.length; i++) {
            String placeholder = "{" + i + "}";
            String argValue = null == args[i] ? StringUtil.EMPTY : args[i].toString();
            msg = msg.replace(placeholder, argValue);
        }
        return msg;
    }
}
